<template>
  <div class="application-list-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>测试申请单列表</span>
          <el-button type="primary" @click="handleCreateApplication" v-if="hasRole('PRODUCT_MANAGER')">发起测试申请</el-button>
        </div>
      </template>
      
      <!-- 搜索和筛选 -->
      <div class="search-filter">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="产品名称">
            <el-select
              v-model="searchForm.productId"
              placeholder="请选择产品"
              style="width: 150px"
              @change="handleProductChange"
            >
              <el-option label="全部" value=""></el-option>
              <el-option
                v-for="product in productList"
                :key="product.id"
                :label="product.productName"
                :value="product.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="版本号">
            <el-select
              v-model="searchForm.versionId"
              placeholder="请选择版本"
              style="width: 150px"
              :disabled="!searchForm.productId"
            >
              <el-option label="全部" value=""></el-option>
              <el-option
                v-for="version in versionList"
                :key="version.id"
                :label="version.versionName"
                :value="version.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="申请状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择申请状态"
              style="width: 120px"
            >
              <el-option label="全部" value=""></el-option>
              <el-option label="待审核" value="0"></el-option>
              <el-option label="已通过" value="1"></el-option>
              <el-option label="已拒绝" value="2"></el-option>
              <el-option label="已撤销" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 申请单表格 -->
      <div class="application-table">
        <el-table
          :data="applicationList"
          style="width: 100%"
          border
        >
          <el-table-column prop="id" label="申请单ID" width="100"></el-table-column>
          <el-table-column prop="productName" label="产品名称" width="150"></el-table-column>
          <el-table-column prop="versionName" label="版本号" width="120"></el-table-column>
          <el-table-column prop="description" label="申请说明"></el-table-column>
          <el-table-column prop="status" label="申请状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="申请时间" width="180"></el-table-column>
          <el-table-column prop="creatorName" label="申请人" width="100"></el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleViewApplication(scope.row)">查看</el-button>
              <template v-if="scope.row.status === 0">
                <el-button type="warning" size="small" @click="handleEditApplication(scope.row)">编辑</el-button>
                <el-button type="danger" size="small" @click="handleCancelApplication(scope.row.id)">撤销</el-button>
              </template>
              <template v-if="hasRole('TEST_MANAGER') && scope.row.status === 0">
                <el-button type="success" size="small" @click="handleApproveApplication(scope.row)">审核通过</el-button>
                <el-button type="error" size="small" @click="handleRejectApplication(scope.row)">审核拒绝</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 查看申请单对话框 -->
    <el-dialog
      v-model="viewDialog.visible"
      title="测试申请单详情"
      width="700px"
    >
      <div class="application-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="申请单ID">{{ viewDialog.data.id }}</el-descriptions-item>
          <el-descriptions-item label="产品名称">{{ viewDialog.data.productName }}</el-descriptions-item>
          <el-descriptions-item label="版本号">{{ viewDialog.data.versionName }}</el-descriptions-item>
          <el-descriptions-item label="申请说明">{{ viewDialog.data.description }}</el-descriptions-item>
          <el-descriptions-item label="申请状态">{{ getStatusText(viewDialog.data.status) }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ viewDialog.data.createTime }}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{ viewDialog.data.creatorName }}</el-descriptions-item>
          <el-descriptions-item label="审核意见" v-if="viewDialog.data.auditOpinion">{{ viewDialog.data.auditOpinion }}</el-descriptions-item>
          <el-descriptions-item label="审核人" v-if="viewDialog.data.auditorName">{{ viewDialog.data.auditorName }}</el-descriptions-item>
          <el-descriptions-item label="审核时间" v-if="viewDialog.data.auditTime">{{ viewDialog.data.auditTime }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import router from '../../router'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'ApplicationList',
  setup() {
    const searchForm = ref({
      productId: '',
      versionId: '',
      status: ''
    })
    
    const productList = ref([])
    const versionList = ref([])
    const applicationList = ref([])
    
    const pagination = ref({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    const viewDialog = ref({
      visible: false,
      data: {}
    })
    
    const userInfo = ref({})
    
    // 初始化数据
    onMounted(() => {
      // 获取用户信息
      const storedUserInfo = localStorage.getItem('userInfo')
      if (storedUserInfo) {
        userInfo.value = JSON.parse(storedUserInfo)
      }
      
      fetchProductList()
      fetchApplicationList()
    })
    
    // 获取产品列表
    const fetchProductList = async () => {
      try {
        const response = await axios.get('/api/products')
        if (response.data.code === 200) {
          productList.value = response.data.data.list || []
        }
      } catch (error) {
        // 使用模拟数据
        productList.value = [
          { id: 1, productName: '测试系统A' },
          { id: 2, productName: '测试系统B' },
          { id: 3, productName: '测试系统C' }
        ]
      }
    }
    
    // 产品变更时获取版本列表
    const handleProductChange = async () => {
      if (!searchForm.value.productId) {
        versionList.value = []
        return
      }
      
      try {
        const response = await axios.get(`/api/product/${searchForm.value.productId}/versions`)
        if (response.data.code === 200) {
          versionList.value = response.data.data
        }
      } catch (error) {
        console.error('获取版本列表失败:', error)
        // 使用模拟数据
        versionList.value = [
          { id: 1, versionName: 'V1.0.0' },
          { id: 2, versionName: 'V1.0.1' },
          { id: 3, versionName: 'V1.0.2' }
        ]
      }
    }
    
    // 获取申请单列表
    const fetchApplicationList = async () => {
      try {
        const response = await axios.get('/api/application/list', {
          params: {
            ...searchForm.value,
            currentPage: pagination.value.currentPage,
            pageSize: pagination.value.pageSize
          }
        })
        
        if (response.data.code === 200) {
          applicationList.value = response.data.data.list
          pagination.value.total = response.data.data.total
        }
      } catch (error) {
        // 使用模拟数据
        applicationList.value = [
          {
            id: 1,
            productId: 1,
            productName: '测试系统A',
            versionId: 1,
            versionName: 'V1.0.0',
            description: '测试系统A V1.0.0版本功能测试申请',
            status: 1,
            createTime: '2025-08-25 10:00:00',
            creatorName: '张三',
            auditOpinion: '同意测试',
            auditorName: '李四',
            auditTime: '2025-08-25 15:30:00'
          },
          {
            id: 2,
            productId: 2,
            productName: '测试系统B',
            versionId: 2,
            versionName: 'V1.0.1',
            description: '测试系统B V1.0.1版本回归测试申请',
            status: 0,
            createTime: '2025-08-26 11:00:00',
            creatorName: '王五'
          },
          {
            id: 3,
            productId: 3,
            productName: '测试系统C',
            versionId: 3,
            versionName: 'V1.0.2',
            description: '测试系统C V1.0.2版本性能测试申请',
            status: 2,
            createTime: '2025-08-27 12:00:00',
            creatorName: '赵六',
            auditOpinion: '版本未准备就绪，暂时驳回',
            auditorName: '钱七',
            auditTime: '2025-08-27 16:30:00'
          }
        ]
        pagination.value.total = applicationList.value.length
      }
    }
    
    // 搜索申请单
    const handleSearch = () => {
      pagination.value.currentPage = 1
      fetchApplicationList()
    }
    
    // 重置搜索条件
    const handleReset = () => {
      searchForm.value = {
        productId: '',
        versionId: '',
        status: ''
      }
      versionList.value = []
      pagination.value.currentPage = 1
      fetchApplicationList()
    }
    
    // 分页大小变化
    const handleSizeChange = (size) => {
      pagination.value.pageSize = size
      fetchApplicationList()
    }
    
    // 分页页码变化
    const handleCurrentChange = (current) => {
      pagination.value.currentPage = current
      fetchApplicationList()
    }
    
    // 创建测试申请
    const handleCreateApplication = () => {
      // 跳转到创建测试申请页面
      router.push('/dashboard/application/create')
    }
    
    // 查看申请单详情
    const handleViewApplication = (row) => {
      viewDialog.data = { ...row }
      viewDialog.visible = true
    }
    
    // 编辑申请单
    const handleEditApplication = (row) => {
      // 跳转到编辑测试申请页面
      router.push({ path: '/dashboard/application/edit', query: { id: row.id } })
    }
    
    // 撤销申请单
    const handleCancelApplication = (id) => {
      ElMessageBox.confirm('确定要撤销该测试申请单吗？撤销后将无法恢复。', '确认撤销', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await axios.put(`/api/application/${id}/cancel`)
          
          if (response.data.code === 200) {
            ElMessage.success('撤销成功')
            fetchApplicationList()
          } else {
            ElMessage.error(response.data.message || '撤销失败')
          }
        } catch (error) {
          console.error('撤销申请单失败:', error)
          ElMessage.error('撤销失败，请检查网络或稍后重试')
        }
      }).catch(() => {
        // 用户取消撤销
      })
    }
    
    // 审核通过申请单
    const handleApproveApplication = (row) => {
      ElMessageBox.prompt('请输入审核意见', '审核通过', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{0,200}$/,
        inputErrorMessage: '审核意见不超过200个字符'
      }).then(async ({ value }) => {
        try {
          const response = await axios.put(`/api/application/${row.id}/approve`, {
            auditOpinion: value
          })
          
          if (response.data.code === 200) {
            ElMessage.success('审核通过成功')
            fetchApplicationList()
          } else {
            ElMessage.error(response.data.message || '审核通过失败')
          }
        } catch (error) {
          console.error('审核通过申请单失败:', error)
          ElMessage.error('审核通过失败，请检查网络或稍后重试')
        }
      }).catch(() => {
        // 用户取消审核
      })
    }
    
    // 审核拒绝申请单
    const handleRejectApplication = (row) => {
      ElMessageBox.prompt('请输入拒绝原因', '审核拒绝', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{0,200}$/,
        inputErrorMessage: '拒绝原因不超过200个字符'
      }).then(async ({ value }) => {
        try {
          const response = await axios.put(`/api/application/${row.id}/reject`, {
            auditOpinion: value
          })
          
          if (response.data.code === 200) {
            ElMessage.success('审核拒绝成功')
            fetchApplicationList()
          } else {
            ElMessage.error(response.data.message || '审核拒绝失败')
          }
        } catch (error) {
          console.error('审核拒绝申请单失败:', error)
          ElMessage.error('审核拒绝失败，请检查网络或稍后重试')
        }
      }).catch(() => {
        // 用户取消审核
      })
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 0:
          return '待审核'
        case 1:
          return '已通过'
        case 2:
          return '已拒绝'
        case 3:
          return '已撤销'
        default:
          return '未知状态'
      }
    }
    
    // 获取状态标签类型
    const getStatusTagType = (status) => {
      switch (status) {
        case 0:
          return 'warning'
        case 1:
          return 'success'
        case 2:
          return 'danger'
        case 3:
          return 'info'
        default:
          return 'default'
      }
    }
    
    // 判断用户是否有指定角色
    const hasRole = (role) => {
      if (!userInfo.value || !userInfo.value.roles) return false
      return userInfo.value.roles.includes(role)
    }
    
    return {
      searchForm,
      productList,
      versionList,
      applicationList,
      pagination,
      viewDialog,
      userInfo,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleProductChange,
      handleCreateApplication,
      handleViewApplication,
      handleEditApplication,
      handleCancelApplication,
      handleApproveApplication,
      handleRejectApplication,
      getStatusText,
      getStatusTagType,
      hasRole
    }
  }
}
</script>

<style scoped>
.application-list-container {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.el-card {
  border-radius: 12px;
  overflow: hidden;
  border: none;
  transition: all 0.3s ease;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.el-card:hover {
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
}

.card-header span {
  font-size: 18px;
  font-weight: 600;
}

.card-header .el-button {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  transition: all 0.3s ease;
}

.card-header .el-button:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.05);
}

.search-filter {
  margin: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-filter .el-form-item {
  margin-bottom: 10px;
}

.application-table {
  margin: 0 20px 20px 20px;
  padding: 10px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.application-table .el-table {
  border: none;
}

.application-table .el-table__header-wrapper th {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
  border-bottom: none;
}

.application-table .el-table__body-wrapper {
  border: 1px solid #e9ecef;
  border-radius: 0 0 8px 8px;
}

.application-table .el-table__row {
  transition: all 0.2s ease;
}

.application-table .el-table__row:hover {
  background: #f5f7fa;
  transform: scale(1.01);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.pagination {
  margin: 0 20px 20px 20px;
  display: flex;
  justify-content: flex-end;
}

.pagination .el-pagination {
  background: white;
  padding: 12px 16px;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.application-detail {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.application-detail .el-descriptions {
  border: 1px solid #e9ecef;
  border-radius: 8px;
  overflow: hidden;
}

.application-detail .el-descriptions__row {
  transition: all 0.2s ease;
}

.application-detail .el-descriptions__row:hover {
  background: #e9ecef;
}

.application-detail .el-descriptions__label {
  font-weight: 600;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-right: 1px solid #e9ecef;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .application-list-container {
    padding: 10px;
  }
  
  .card-header {
    padding: 16px 20px;
  }
  
  .search-filter, .application-table, .pagination {
    margin: 10px;
  }
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 10px;
    text-align: center;
  }
  
  .search-filter {
    padding: 12px;
  }
  
  .search-filter .el-form {
    flex-direction: column;
  }
  
  .search-filter .el-form-item {
    width: 100%;
  }
  
  .application-table .el-table {
    font-size: 12px;
  }
}
</style>